package com.suning.sawp.service.impl.esb;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.suning.rsc.dto.responsedto.MbfResponse;
import com.suning.rsc.httpservice.annotation.EsbEIHttpWired;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.dto.customer.MemberQueryBindPhone;
import com.suning.sawp.dto.esb.AccountAlias;
import com.suning.sawp.dto.esb.BindKGPartyToPartyBody;
import com.suning.sawp.dto.esb.BindKGPartyToPartyReq;
import com.suning.sawp.dto.esb.CustNumStruct;
import com.suning.sawp.dto.esb.CustSocietyInfoStruct;
import com.suning.sawp.dto.esb.LocateMemberInfo;
import com.suning.sawp.dto.esb.MemberInfoQueryReq;
import com.suning.sawp.dto.esb.MemberQueryBody;
import com.suning.sawp.dto.esb.MemberQuerySocialityInfoReq;
import com.suning.sawp.dto.esb.QueryBindPhoneReq;
import com.suning.sawp.dto.esb.QueryBindPhoneReqBody;
import com.suning.sawp.dto.esb.QuerySocialityInfoBody;
import com.suning.sawp.dto.esb.QuerySocialityInfoResp;
import com.suning.sawp.intf.esb.MemberAccountMgmtService;
import com.suning.sawp.intf.esb.MemberInfoService;
import com.suning.sawp.intf.esb.MemberQueryService;
import com.suning.sawp.service.util.XmlUtils;

@Service
public class MemberInfoServiceImpl implements MemberInfoService {

	private static final Logger LOGGER = LoggerFactory.getLogger(MemberInfoServiceImpl.class);
	
	private MemberQueryService memberQueryService;
	
	private MemberAccountMgmtService memberAccountMgmtService;
	/**
     * 别名类型: 手机号码
     */
    public static final String ALIASTYPE_MOBILENO = "138000000010";

    /**
     * 别名类型:邮箱
     */
    public static final String ALIASTYPE_EMAIL = "138000000020";
    
    /**
     * 查询手机时,查询别名手机号码,不查询联系手机
     */
    public static final String CNTCTMOBILEFLAG_ALIAS = "100000000020";
	
    private static Pattern emailPattern = 
            Pattern.compile(ClerkConstants.EMAIL_PATTERN);
    
    /**
     * 客户端新人红包
     */
    private static final String APP_NEW_RED_PAPER = "258000000020";
    
    private static final String ESB_SUCCESS_STATUS = "COMPLETE";
    
	public MemberAccountMgmtService getMemberAccountMgmtService() {
        return memberAccountMgmtService;
    }
    @EsbEIHttpWired
    public void setMemberAccountMgmtService(MemberAccountMgmtService memberAccountMgmtService) {
        this.memberAccountMgmtService = memberAccountMgmtService;
    }
    
    public MemberQueryService getMemberQueryService() {
        return memberQueryService;
    }
    @EsbEIHttpWired
    public void setMemberQueryService(MemberQueryService memberQueryService) {
        this.memberQueryService = memberQueryService;
    }

    public LocateMemberInfo locateMemberByMobileNo(String mobileNo) {
        LOGGER.info("locateMemberByMobileNo, mobileNo:{}",mobileNo);
		//修改会员验证接口用esb注解方式  by---吴晓
        LocateMemberInfo memberInfo = null;
        MemberInfoQueryReq req = new MemberInfoQueryReq();
        MemberQueryBody body = new MemberQueryBody();
        body.setAliasName(mobileNo);
        req.setBody(body); 
        MbfResponse response = memberQueryService.queryCouponRule(req);
        if(response != null && response.getOutput() != null){
            Document doc;
            try{
                memberInfo = new LocateMemberInfo();
                doc = XmlUtils.getW3CDom(response.toString());
                memberInfo.setCardNo(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/cardNo"));
                memberInfo.setCertType(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/certType"));
                memberInfo.setCustNum(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/custNum"));
                memberInfo.setHasB2CAcnt(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/hasB2CAcnt"));
                memberInfo.setHasPhysCard(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/hasPhysCard"));
                memberInfo.setInitPassFlag(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/initPassFlag"));
                memberInfo.setMobileNumMain(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/mobileNumMain"));
                memberInfo.setSuccess(true);
            }catch(Exception e){
                LOGGER.error("查询会员信息，解析报文失败，手机号:" + mobileNo,e);
            }
        }else{
            LOGGER.error("未定位出会员信息,定位出错,mobileNo:{}", mobileNo);
        }
        return memberInfo;
	}
    @Override
    public QuerySocialityInfoResp querySocialityInfoAConstellation(List<String> custNumList) {
        QuerySocialityInfoResp infoResp = null;
        MemberQuerySocialityInfoReq req = new MemberQuerySocialityInfoReq();
        QuerySocialityInfoBody body = new QuerySocialityInfoBody();
        List<CustNumStruct> custNumStructList = new ArrayList<CustNumStruct>();
        for (String custNum : custNumList) {
            custNumStructList.add(new CustNumStruct(custNum));
        }
        body.setCustNumStructList(custNumStructList);
        req.setBody(body);
        MbfResponse mbfResponse = memberQueryService.querySocialityInfoAConstellation(req);
        if (null != mbfResponse && null != mbfResponse.getOutput()) {
            infoResp = (QuerySocialityInfoResp) mbfResponse.getOutput().getMbfBody(QuerySocialityInfoResp.class);
        }
        return infoResp;
    }
    
    @Override
    public LocateMemberInfo locateMember(String ebuyNo) {
        LOGGER.debug("MemberInfoService.locateMember, ebuyNo:{}", ebuyNo);
        LocateMemberInfo memberInfo = null;
        MemberInfoQueryReq req = new MemberInfoQueryReq();
        MemberQueryBody body = new MemberQueryBody();
        // 判断邮箱用户
        Matcher emailMatcher = emailPattern.matcher(ebuyNo);
        if (emailMatcher.matches()) {
            body.setAliasType(ALIASTYPE_EMAIL);
        }
        // 其他都按手机用户处理
        body.setAliasName(ebuyNo);
        req.setBody(body);
        MbfResponse response = memberQueryService.queryCouponRule(req);
        if(response != null && response.getOutput() != null){
            Document doc;
            try{
                memberInfo = new LocateMemberInfo();
                doc = XmlUtils.getW3CDom(response.toString());
                memberInfo.setCardNo(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/cardNo"));
                memberInfo.setCertType(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/certType"));
                memberInfo.setCustNum(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/custNum"));
                memberInfo.setHasB2CAcnt(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/hasB2CAcnt"));
                memberInfo.setHasPhysCard(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/hasPhysCard"));
                memberInfo.setInitPassFlag(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/initPassFlag"));
                memberInfo.setMobileNumMain(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/mobileNumMain"));
                memberInfo.setSuccess(true);
            }catch(Exception e){
                LOGGER.error("查询会员信息，解析报文失败，易购账号:" + ebuyNo,e);
            }
        }else{
            LOGGER.error("未定位出会员信息,定位出错,ebuyNo:{}", ebuyNo);
        }
        return memberInfo;
    }
    @Override
    public boolean bindKGPartyToParty(String clerkCustNo, String custNo) {
        LOGGER.debug("MemberInfoService.bindKGPartyToParty, clerkCustNo:{}, custNo:{}", clerkCustNo, custNo);
        boolean flag  = false;// 默认绑定失败
        BindKGPartyToPartyReq req = new BindKGPartyToPartyReq();
        BindKGPartyToPartyBody body = new BindKGPartyToPartyBody();
        body.setCustNum(clerkCustNo);
        body.setExtCustNum(custNo);
        body.setRelSource(APP_NEW_RED_PAPER);
        req.setBody(body);
        MbfResponse response = memberQueryService.bindKGPartyToParty(req);
        if(response != null && response.getOutput() != null
                && ESB_SUCCESS_STATUS.equals(response.getOutput().getMbfHeader().getServiceResponse().getStatus())){
            flag = true;
        }
        return flag;
    }
    @Override
    public Map<String, String> getMemberMobiles(List<String> custNoList) {
        Map<String, String> custMobiles = new HashMap<String, String>();
        QuerySocialityInfoResp infoResp = querySocialityInfoAConstellation(custNoList);
        if (null != infoResp && null != infoResp.getBody()) {
            if (CollectionUtils.isNotEmpty(infoResp.getBody().getCustSocietyInfoStructList())) {
                for (CustSocietyInfoStruct infoStruct : infoResp.getBody().getCustSocietyInfoStructList()) {
                    if (CollectionUtils.isNotEmpty(infoStruct.getAccountAliasList())) {
                        String cmfMobile = null;
                        for (AccountAlias alias : infoStruct.getAccountAliasList()) {
                            if (AccountAlias.AliasType.MOBILE.equals(alias.getAliasType())) {
                                cmfMobile = alias.getAliasName();
                                break;
                            }
                        }
                        custMobiles.put(infoStruct.getCustNum(), cmfMobile);
                    }
                }
            }
        }
        
        return custMobiles;
    }
    @Override
    public MemberQueryBindPhone queryBindPhone(String custNum) {
        QueryBindPhoneReq req = new QueryBindPhoneReq();
        QueryBindPhoneReqBody body = new QueryBindPhoneReqBody();
        body.setCustNum(custNum);
        req.setBody(body);
        MbfResponse resp = memberAccountMgmtService.queryBindPhone(req);
        MemberQueryBindPhone queryBindPhone = null;
        Document doc;
        try{
            if (ESB_SUCCESS_STATUS.equals(resp.getOutput().getMbfHeader().getServiceResponse().getStatus())) {
                queryBindPhone = new MemberQueryBindPhone();
                doc = XmlUtils.getW3CDom(resp.toString());
                queryBindPhone.setMobileNum(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/mobileNum"));
                queryBindPhone.setMobileStat(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/mobileStat"));
                queryBindPhone.setMobileStatUpdTime(XmlUtils.getValueByXpath(doc,
                        "/MbfService/output1/body/mobileStatUpdTime"));
            }
        } catch (Exception e) {
            LOGGER.error("queryBindPhone error, custNum:{}", custNum, e);
        }
        return queryBindPhone;
    }

}
